import axios from "axios";
import { ElMessage, ElLoading } from "element-plus";
import router from "../router";
import Cookies from "js-cookie";
import { debounce } from "lodash";

const isProduction = import.meta.env.PROD;

let loadingInstance;
const LoadingOpts = {
  lock: true,
  text: "加载中……",
  background: "rgba(0, 0, 0, 0.7)",
};

const RequestStack = [];
let RequestId = 0;

const closeLoading = debounce(() => {
  if (!RequestStack.length) {
    loadingInstance && loadingInstance.close();
    loadingInstance = null;
  }
}, 100);

// let baseURL = isProduction ? "http://localhost:5059" : "/api";
let baseURL = isProduction ? "http://120.55.183.212:5059" : "/api";

let config = {
  baseURL,
  // timeout: 60 * 1000 * 10,
  timeout: 0, // 不设置超时时间
};

let instance = axios.create(config);
// 请求拦截
instance.interceptors.request.use(
  function (config) {
    const token = Cookies.get("authToken");
    if (token) {
      config.headers["Token"] = token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // config.headers["Content-Type"] = "application/json";
    if (config.loading) {
      !loadingInstance && (loadingInstance = ElLoading.service(LoadingOpts));
      RequestStack.push(RequestId++);
    }
    return config;
  },
  function (error) {
    RequestStack.pop();
    closeLoading();
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  (res) => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 0;
    // 获取错误信息
    const msg = res.msg || res.data.msg;
    // 二进制数据则直接返回
    if (res.request.responseType === "blob" || res.request.responseType === "arraybuffer") {
      return res;
    }
    RequestStack.pop();
    closeLoading();

    if (code != 200) {
      if (msg.includes("认证失败")) {
        ElMessage({
          message: msg,
          grouping: true,
          type: "warning",
        });
      } else if (msg.includes("token 无效")) {
        router.replace("/");
      } else {
        ElMessage.warning(msg);
      }
      return Promise.reject(msg);
    } else {
      return res.data;
    }
  },
  (err) => {
    if (err.config.url == "/login") {
      ElMessage.warning("请输入正确的用户名或密码！");
    } else if (err.config.url != "/actuator") {
      if (err.code != "ERR_NETWORK") {
        ElMessage({
          message: err.ElMessage,
          type: "error",
        });
      }
    }
    RequestStack.pop();
    closeLoading();
    return Promise.reject(err);
  }
);

export default instance;
